package com.multicampus.simplewiki.webservice;

import java.sql.Timestamp;

import org.springframework.remoting.jaxrpc.ServletEndpointSupport;

import com.multicampus.simplewiki.ctrl.DocumentManager;
import com.multicampus.simplewiki.model.Document;
import com.multicampus.simplewiki.model.User;
import com.multicampus.simplewiki.vo.DocumentVO;
import com.multicampus.simplewiki.vo.UserVO;

public class WikiService  extends ServletEndpointSupport {

	private DocumentManager manager = null;

	public String insertDocument(DocumentVO documentVO, String parentId) {
		this.manager = (DocumentManager) getWebApplicationContext().getBean("documentManager");
		Document document = getDocument(documentVO);
		document = manager.insertDocument(document, parentId);
		return "success";
	}

	public DocumentVO findDocument(int documentId) {
		this.manager = (DocumentManager) getWebApplicationContext().getBean("documentManager");
		Document document = manager.findDocument(documentId);
		return getDocumentVO(document);
	}

	private Document getDocument(DocumentVO documentVO) {
		Document document = new Document();
		document.setId(documentVO.getId());
		document.setTitle(documentVO.getTitle());
		document.setContent(documentVO.getContent());
		document.setTags(documentVO.getTags());
		document.setCreationDate(new Timestamp(documentVO.getCreationDate()));
		document.setUpdateDate(new Timestamp(documentVO.getUpdateDate()));
		if ( documentVO.getAuthor()!=null ) {
			UserVO userVO = documentVO.getAuthor();
			User user = new User();
			user.setEmail(userVO.getEmail());
			user.setId(userVO.getId());
			user.setName(userVO.getName());
			document.setAuthor(user);
		}
		return document;
	}

	private DocumentVO getDocumentVO(Document document) {
		DocumentVO documentVO = new DocumentVO();
		documentVO.setId(document.getId());
		documentVO.setTitle(document.getTitle());
		documentVO.setContent(document.getContent());
		documentVO.setTags(document.getTags());
		documentVO.setCreationDate(document.getCreationDate().getTime());
		documentVO.setUpdateDate(document.getUpdateDate().getTime());
		if ( document.getAuthor()!=null ) {
			User user = document.getAuthor();
			UserVO userVO = new UserVO();
			userVO.setEmail(user.getEmail());
			userVO.setId(user.getId());
			userVO.setName(user.getName());
			documentVO.setAuthor(userVO);
		}
		return documentVO;
	}
}